package net.myspring.common.config;

import net.myspring.common.utils.Const;
import net.myspring.common.utils.StringUtils;
import net.myspring.common.utils.ThreadLocalContext;
import net.myspring.middle.domain.Account;
import net.myspring.middle.security.CustomUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * Created by liuj on 2016-08-20.
 */
public class MyHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Account account = null;
        if(request.getParameter("companyName") != null) {
            String companyName = StringUtils.toString(request.getParameter("companyName"));
            ThreadLocalContext.get().setCompanyName(companyName);
        }
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(Const.CookieEnum.SIDEBAR_CLASS.getValue())) {
                    request.getSession().setAttribute(cookie.getName(), URLDecoder.decode(cookie.getValue(), Const.CharEnum.UTF8.getValue()));
                }
            }
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getPrincipal().getClass().isAssignableFrom(CustomUserDetails.class)) {
                account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
            }
            ThreadLocalContext.get().setAccount(account);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalContext.get().remove();
    }
}